<?php

/**
 * Created by PhpStorm.
 * User: root
 * Date: 2017/10/26 0026
 * Time: 10:13
 */
namespace app\wxapp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wxapp\model\Wxapp as WxappModel;
use app\wxapp\model\Attachment as AttachmentModel;

class Package extends Admin
{
    public function index()
    {
        $order = $this->getOrder('id desc');
        $data = WxappModel::where('is_delete = 0')->join('(dp_admin_attachment)', '(dp_admin_attachment.id=dp_wxapp.img)', 'left')->field('dp_wxapp.*, dp_admin_attachment.path')->order($order)->paginate();
        $page = $data->render();

        return ZBuilder::make('table')
            ->setPageTitle('小程序包管理')
            ->setTableName('wxapp')
            ->setSearch(['id' => 'ID', 'title' => '模板名称'])
            ->addColumns([
                ['id', 'ID'],
                ['title', '模板名称', 'text'],
                ['path', '模板图片', 'img_url'],
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,delete')
            ->addRightButtons('edit,delete')
            ->setRowList($data)
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {
        $role = session('user_auth.role');
        if ($role != 1) {
            $this->error('禁止非超级管理员操作');
        }
        if($this->request->isPost()) {
            $data = $this->request->post();
            $data['title'] = addslashes($data['title']);
            $result = $this->validate($data, 'Wxapp');
            if(true !== $result) $this->error($result);
            if ($wxapp = WxappModel::create($data)) {
                $img = AttachmentModel::where('id', $data['img'])->field('path')->find();
                $erweima = AttachmentModel::where('id', $data['erweima'])->field('path')->find();

                //同步到第三方数据
                $package = $this->thirdPackage($data, $img['path'], $erweima['path']);
                // 记录行为
                action_log('wxapp_edit', 'wxapp', $wxapp['id'], UID);
                $this->success('新增成功',url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        return ZBuilder::make('form')
            ->setPageTitle('新增')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'title', '模板名称'],
                ['text', 'filepath', '下载地址'],
                ['text', 'themes', '模板分类id'],
                ['text', 'templateid', '模板id'],
                ['image', 'img', '模板图片'],
                ['image', 'erweima', '二维码图片'],
            ])
        ->layout([
            'title'    => 4,
            'filepath' => 8,
            'themes'   => 4,
            'templateid'=> 5,
            'img'=> 4,
            'erweima'=> 4,

        ])
        ->fetch();
    }

    public function edit($id = null)
    {
        $role = session('user_auth.role');
        if($id === null) {
            $this->error('缺少参数');
        }
        if ($role != 1) {
            $this->error('禁止非超级管理员操作');
        }
        if($this->request->isPost()) {
            $data = $this->request->post();
            $data['title'] = addslashes($data['title']);
            $result = $this->validate($data, 'Wxapp.save');
            if(true !== $result) $this->error($result);
            if ($wxapp = WxappModel::update($data)) {
                $img = AttachmentModel::where('id', $data['img'])->field('path')->find();
                $erweima = AttachmentModel::where('id', $data['erweima'])->field('path')->find();

                //同步到第三方数据
                $package = $this->thirdPackage($data, $img['path'], $erweima['path']);
                // 记录行为
                action_log('wxapp_edit', 'wxapp', $wxapp['id'], UID, get_nickname($wxapp['id']));
                $this->success('编辑成功',url('index'));
            } else {
                $this->error('编辑失败');
            }
        }
        $info = WxappModel::where('id', $id)->find();
        return ZBuilder::make('form')
            ->setPageTitle('编辑')
            ->addFormItems([
                ['hidden', 'id'],
                ['text', 'title', '模板名称'],
                ['text', 'filepath', '下载地址'],
                ['text', 'themes', '模板分类id'],
                ['text', 'templateid', '模板id'],
                ['image', 'img', '模板图片'],
                ['image', 'erweima', '二维码图片'],
            ])
            ->layout([
                'title'    => 4,
                'filepath' => 8,
                'themes'   => 4,
                'templateid'=> 5,
                'img'=> 4,
                'erweima'=> 4,

            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除小程序包
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        $param = $this->request->param();
        $ids = $param['ids'];
        $where['id'] = $ids;
        if (is_array($ids)) {
            $where['id'] = array('in', $ids);
        }
        $data['is_delete'] = 1;
        $result = WxappModel::where($where)->update($data);
        if ($result) {
            $this->success('删除成功', url('index'));
        } else {
            $this->error('删除失败');
        }
    }

    // 请求第三方接口
    public function thirdPackage($data, $img, $erweima){

        $params['title'] = $data['title'];
        $params['filepath'] = $data['filepath'];
        $params['themes'] = $data['themes'];
        $params['templateid'] = $data['templateid'];
        $params['img'] = $img;
        $params['erweima'] = $erweima;
        $opts = [
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => 'https://popular.vdongchina.com/web/index.php?c=api&a=register',
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => $params
        ];

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result  = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
        if ($result['code']==0) {
            return $result['data'];
        } else {
            $this->error($result['message']);
        }

    }

}